import React, { useEffect } from 'react';
import { Button, Dropdown, Menu } from 'antd';
import { Link, useSelector, useDispatch, Switch, Route, Redirect, useHistory } from 'umi';
import Layout, { Content, Header } from 'antd/lib/layout/layout';
import Text from 'antd/lib/typography/Text';
import { request, selectedKeysByPath } from '@/utils';

export default () => {
  const history = useHistory()
  const dispatch = useDispatch()
  const { currentUser } = useSelector(({ global }: { global: any }) => global)
  useEffect(() => {
    getUserInfo()
  }, [])
  const getUserInfo = async () => {
    if (window.getToken) {
      let token = await window.getToken()
      localStorage.token = token
      request("user/info", {}, res => {
        dispatch({ type: "global/saveCurrentUser", currentUser: res })
      }, res => console.log(res))
    }
  }
  return (
    <Layout style={{
    }}>
      <Header style={{
        display: 'flex',
        flexDirection: 'row',
        alignItems: 'center',
        background: '#001529',
      }}>
        <h1 style={{
          height: 32,
          margin: 16,
          color: 'white',
          width: 200
        }}>章鱼工具箱</h1>
        <div style={{
          flex: 1
        }}></div>
        <Menu theme="dark" mode="horizontal" selectedKeys={selectedKeysByPath(history, ["/games", "/backup", "/tools"])}>
          <Menu.Item key="/games" style={{
            height: 64,
            paddingTop: 20
          }}>
            <Link to="/games">游戏</Link>
          </Menu.Item>
          <Menu.Item key="/backup" style={{
            height: 64,
            paddingTop: 20
          }}>
            <Link to="/backup">备份</Link>
          </Menu.Item>
          <Menu.Item key="/tools" style={{
            height: 64,
            paddingTop: 20
          }}>
            <Link to="/tools">工具</Link>
          </Menu.Item>
        </Menu>

        <Text style={{
          color: 'white',
          marginRight: 16,
          marginLeft: 16
        }}>
          {currentUser.Id ?
            <Dropdown overlay={<Menu>
              <Menu.Item onClick={() => {
                dispatch({ type: "global/logout" })
              }}>
                退出
              </Menu.Item>
            </Menu>}>
              <div>{currentUser.Name}</div>
            </Dropdown>
            : <Link to="/login">登录</Link>}
        </Text>

      </Header>
      <Content style={{
      }}>
        <Switch>
          <Route path="/games" component={require("./games").default}></Route>
          <Route path="/backup" component={require("./backup").default}></Route>
          <Route path="/tools" component={require("./tools").default}></Route>
          <Redirect to="/games" />
        </Switch>
      </Content>
    </Layout>
  );
};
